package com.atguigu.safe;

import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CopyOnWriteArraySet;

public class NosafeDemo {
    public static void main(String[] args) {
        Map<String, String> map =new ConcurrentSkipListMap<>(); //Collections.synchronizedMap(new HashMap<>());//new HashMap<>();
        for (int i = 1; i <=100; i++) {
            new Thread(()->{
                map.put(Thread.currentThread().getName(),UUID.randomUUID().toString().substring(0,6));
                System.out.println(map);
            }).start();

        }
    }
    public static void set() {
        Set<String> set =new CopyOnWriteArraySet<>(); //Collections.synchronizedSet(new HashSet<>()); //new HashSet<>();
        for (int i = 1; i <=100; i++) {
            new Thread(()->{
                set.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(set);
            }).start();

        }
    }
    public static void list (){
        //ArrayList没加锁效率高,发生并发修改异常
        //解决方法:1使用Vector线程安全,使用Collection中的sync的方法
        //        2使用juc提供的方法对写操作进行加锁, 读写分离 写时复制(读多写少)
        List<String> list = new CopyOnWriteArrayList<>();//Collections.synchronizedList(new ArrayList<>()); //new Vector<>();//ArrayList<>();
        for (int i = 1; i <=100; i++) {
            new Thread(()->{
                list.add(UUID.randomUUID().toString().substring(0,6));
                System.out.println(list);
            }).start();

        }


    }
}
